/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dk.rofl.graphics;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
 *
 * @author menderleit
 */
public class GameTileSet {

    private BufferedImage[] tiles;
    private int tileSize;

    // Constructor
    // Loads the tiles from an image file into separate images.
    public GameTileSet(String fileName, int tileSize) throws IOException {
        GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();

        File f = new File(fileName);
        BufferedImage img = ImageIO.read(f);
        tiles = new BufferedImage[(img.getWidth() / tileSize) * (img.getHeight() / tileSize)];
        this.tileSize = tileSize;

        int tileNum = 0;
        for (int y = 0; y < img.getHeight() / tileSize; y++) {
            for (int x = 0; x < img.getWidth() / tileSize; x++) {
                BufferedImage bImg = gc.createCompatibleImage(tileSize, tileSize, BufferedImage.TRANSLUCENT);

                Graphics2D g = (Graphics2D) bImg.getGraphics();
                g.setComposite(AlphaComposite.Src);
                g.setColor(new Color(0, 0, 0, 0));
                g.fillRect(0, 0, bImg.getWidth(), bImg.getHeight());
                g.drawImage(img, null, 0 - x * tileSize, 0 - y * tileSize);
                g.dispose();
                tiles[tileNum++] = bImg;
            }
        }
    }

    // Returns the image of the specified Tile, or null if the index is out of bounds.
    public BufferedImage getTileImage(int index) {
        BufferedImage img = null;
        if (index >= 0 && index < tiles.length) {
            img = tiles[index];
        }
        return img;
    }
    
    // Returns the size in pixels of each Tile.
    public int getTileSize() {
        return tileSize;
    }
    
    // Returns the number of tiles in this TileSet.
    public int getNumTiles() {
        return tiles.length;
    }
}
